package com.coe3.datahandler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;

public class FetchQueue {
    public static final int MAX_CONNECTIONS = 2;
 
    private ArrayList<Handler> active = new ArrayList<Handler>();
    private ArrayList<Handler> queue = new ArrayList<Handler>();
    private final Map<Handler, String> handlermap;
 
    private static FetchQueue instance;
    private DrawableManager drawableManager = null;
    
    public void setDrawableManager( DrawableManager manager ) {
    	this.drawableManager = manager;
    }

    public FetchQueue() {
        handlermap = new HashMap<Handler, String>();
    }
 
    public static FetchQueue getInstance() {
        if (instance == null) {
            instance = new FetchQueue();
        }
        return instance;
    }
 
    public void push( Handler handler, String url ) {
    	handlermap.put( handler, url );
        queue.add( handler );
        if( active.size() < MAX_CONNECTIONS )
            startNext();
    }
 
    private void startNext() {
        if ( !queue.isEmpty() ) {
        	final Handler handler = queue.get(0);
            queue.remove(0);
            active.add( handler );

            Thread thread = new Thread() {
            	@Override
            	public void run() {
            		Drawable drawable = drawableManager.fetchDrawable( handlermap.get( handler ) );
            		Message message = handler.obtainMessage( 1, drawable );
            		handler.sendMessage( message );
            	}
            };
            thread.start();
        }
    }
 
    public void didComplete( Handler handler ) {
    	handlermap.remove( handler );
        active.remove( handler );
        startNext();
    }
    
    public void cleanUp() {
    	active.clear();
    	queue.clear();
    }

}
